﻿using System;
using System.Windows;
using System.Windows.Interactivity;
using System.Windows.Media.Animation;
using PairingMatrix.ViewModel;

namespace PairingMatrix.View.Behavior
{
    public class RotateMingleSyncToolBarBehavior : Behavior<ToolBarControl>
    {
        private ToolBarViewModel _toolBarViewModel;
        private Storyboard _storyboard;
        private DoubleAnimation _rotateAnimation;

        protected override void OnAttached()
        {
            AssociatedObject.Loaded += (sender, e) =>
            {
                _toolBarViewModel = (ToolBarViewModel)AssociatedObject.DataContext;
                _toolBarViewModel.PropertyChanged += ToolBarPropertyChanged;

                _rotateAnimation = new DoubleAnimation();
                TimeSpan duration = TimeSpan.FromMilliseconds(500);
                _rotateAnimation.Duration = duration;
                _rotateAnimation.RepeatBehavior = RepeatBehavior.Forever;
                _storyboard = new Storyboard();
                _storyboard.Duration = duration;
                _storyboard.Children.Add(_rotateAnimation);
                Storyboard.SetTarget(_rotateAnimation, AssociatedObject.rotateTransform);
                Storyboard.SetTargetProperty(_rotateAnimation, new PropertyPath("Angle"));
                _storyboard.Completed += new EventHandler(_storyboard_Completed);
            };

        }

        void _storyboard_Completed(object sender, EventArgs e)
        {
            AssociatedObject.rotateTransform.Angle = 0;
            _rotateAnimation.To = 360;
            _storyboard.Begin();
        }

        void ToolBarPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "IsSyncingAllProjectCards")
            {
                if (_toolBarViewModel.IsSyncingAllProjectCards)
                {
                    _rotateAnimation.To = 360;
                    _storyboard.Begin();
                }
                else
                {
                    _storyboard.Stop();
                }
            }
        }

    }
}
